/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

/*
 * ImportWorldsFrame.java
 *
 * Created on Jun 24, 2011, 11:18:06 AM
 */

package net.worlds.component;

import java.io.IOException;
import java.util.HashMap;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.swing.BoxLayout;
import javax.swing.ImageIcon;
import javax.swing.SwingUtilities;
import net.worlds.Main;
import net.worlds.Util;
import net.worlds.World;

/**
 *
 * @author Jacob Morgan
 */
public class ImportWorldsFrame extends javax.swing.JFrame {
    private HashMap<String, ImportWorldsListItem> items = new HashMap<String, ImportWorldsListItem>(32);
    private String filePath;
    /** Creates new form ImportWorldsFrame */
    public ImportWorldsFrame() {
        initComponents();
        setTitle("Import Worlds");
        setLocationRelativeTo(Main.getApplet());
        try
        {
            setIconImages(Util.icons);
        }
        catch(Exception ex)
        {
            ex.printStackTrace();
        }
        worldsPanel.setLayout(new BoxLayout(worldsPanel, BoxLayout.Y_AXIS));
    }
    public void showWorlds(String filePath)
    {
        this.filePath = filePath;
        try {
            String text = Util.readFileAsString(filePath);
            if(!text.contains("|:;||||::"))
            {
                System.out.println("Error: This game is in the old format! Resave it before importing.");
                SwingUtilities.invokeLater(new Runnable()
                {
                    public void run() {
                        dispose();
                    }
                });
                return;
            }
            String[] parts = text.split("\\|:;\\|\\|\\|\\|::");
            for(String p : parts)
            {
                String part = p.trim();
                final String world = part.split("\n")[0].replace("--World: ", "");
                if(!world.isEmpty())
                {
                    SwingUtilities.invokeLater(new Runnable()
                    {
                        public void run() {
                            ImportWorldsListItem item = new ImportWorldsListItem(world);
                            item.setSize(262, 42);
                            worldsPanel.add(item);
                            items.put(world, item);
                        }
                    });
                }
            }
        } catch (IOException ex) {

        }
    }

    private void doImport()
    {
        Main.runInMainThread(new Runnable()
        {
            public void run() {
                try {
                    String text = Util.readFileAsString(filePath);
                    String[] parts = text.split("\\|:;\\|\\|\\|\\|::");
                    for (String p : parts) {
                        String part = p.trim();
                        final String world = part.split("\n")[0].replace("--World: ", "");
                        if (!world.isEmpty()) {
                            ImportWorldsListItem item = items.get(world);
                            if(item != null && item.shouldImport())
                            {
                                String newName = item.getNewName();
                                if(!Main.getGame().getWorlds().containsKey(newName))
                                {
                                    World newWorld = Main.getGame().createWorld(newName);
                                    Main.getScriptContext().setGame(newWorld);
                                    Main.getScriptContext().executeScript(part);
                                }
                                else
                                {
                                    System.out.println("World named "+newName+" already exists; not importing.");
                                }
                            }
                        }
                    }
                } catch (Exception ex) {
                    ex.printStackTrace();
                }
                SwingUtilities.invokeLater(new Runnable()
                {
                    public void run() {
                        dispose();
                    }
                });
            }
        });
    }

    /** This method is called from within the constructor to
     * initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is
     * always regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        listScroller = new javax.swing.JScrollPane();
        worldsPanel = new javax.swing.JPanel();
        cancelButton = new javax.swing.JButton();
        okButton = new javax.swing.JButton();
        infoLabel = new javax.swing.JLabel();

        setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
        setResizable(false);

        javax.swing.GroupLayout worldsPanelLayout = new javax.swing.GroupLayout(worldsPanel);
        worldsPanel.setLayout(worldsPanelLayout);
        worldsPanelLayout.setHorizontalGroup(
            worldsPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGap(0, 266, Short.MAX_VALUE)
        );
        worldsPanelLayout.setVerticalGroup(
            worldsPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGap(0, 254, Short.MAX_VALUE)
        );

        listScroller.setViewportView(worldsPanel);

        cancelButton.setText("Cancel");
        cancelButton.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                cancelButtonActionPerformed(evt);
            }
        });

        okButton.setText("OK");
        okButton.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                okButtonActionPerformed(evt);
            }
        });

        infoLabel.setText("Select worlds to import and their new names:");

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(listScroller, javax.swing.GroupLayout.DEFAULT_SIZE, 285, Short.MAX_VALUE)
                    .addGroup(layout.createSequentialGroup()
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
                            .addGroup(layout.createSequentialGroup()
                                .addComponent(infoLabel)
                                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
                            .addGroup(layout.createSequentialGroup()
                                .addComponent(okButton)
                                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)))
                        .addComponent(cancelButton)))
                .addContainerGap())
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
                .addGap(11, 11, 11)
                .addComponent(infoLabel)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addComponent(listScroller, javax.swing.GroupLayout.DEFAULT_SIZE, 244, Short.MAX_VALUE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(cancelButton)
                    .addComponent(okButton))
                .addContainerGap())
        );

        pack();
    }// </editor-fold>//GEN-END:initComponents

    private void cancelButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_cancelButtonActionPerformed
        dispose();
    }//GEN-LAST:event_cancelButtonActionPerformed

    private void okButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_okButtonActionPerformed
        doImport();
    }//GEN-LAST:event_okButtonActionPerformed

    /**
    * @param args the command line arguments
    */
    public static void main(String args[]) {
        java.awt.EventQueue.invokeLater(new Runnable() {
            public void run() {
                new ImportWorldsFrame().setVisible(true);
            }
        });
    }

    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JButton cancelButton;
    private javax.swing.JLabel infoLabel;
    private javax.swing.JScrollPane listScroller;
    private javax.swing.JButton okButton;
    private javax.swing.JPanel worldsPanel;
    // End of variables declaration//GEN-END:variables

}
